import {fetchDemo} from '@apis/demo';
import {createAsyncThunk, createSlice} from '@reduxjs/toolkit';
import {RootState} from '../index';
// Define a type for the slice state

// Define the initial state using that type
const initialState = {
    value: 'init state',
};

export const fetchDemoAsync = createAsyncThunk('demo/fetchDemo', async (name: string) => {
    return fetchDemo(name);
});

export const demoSlice = createSlice({
    name: 'demo',
    initialState,
    reducers: {},
    extraReducers: (builder) => {
        builder
            .addCase(fetchDemoAsync.pending, (state) => {
                console.log('请求中');
            })
            .addCase(fetchDemoAsync.fulfilled, (state, action) => {
                state.value = action.payload.data;
            })
            .addCase(fetchDemoAsync.rejected, (state) => {
                console.log('请求失败');
            });
    },
});

// Other code such as selectors can use the imported `RootState` type
export const selectDemoValue = (state: RootState) => state.demo.value;

export default demoSlice.reducer;
